<template>
  <div class="p-4">
    <el-card class="mb-4">
      <template #header>
        <div class="flex justify-between items-center">
          <h3 class="font-semibold text-lg">商品管理</h3>
          <el-button type="primary" @click="handleAddProduct">添加商品</el-button>
        </div>
      </template>
      
      <!-- 搜索筛选区域 -->
      <el-form :inline="true" :model="searchForm" class="mb-4">
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
            <el-option label="全部" value="" />
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="上架" value="active" />
            <el-option label="下架" value="inactive" />
            <el-option label="审核中" value="pending" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table
        :data="productList"
        stripe
        border
        fit
        highlight-current-row
        @row-dblclick="handleEditProduct"
      >
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column label="商品图片" width="100">
          <template #default="scope">
            <el-image
              :src="scope.row.images[0] || 'https://picsum.photos/seed/default/60/60'"
              :preview-src-list="scope.row.images"
              class="w-12 h-12 object-cover rounded"
              fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商品名称" min-width="180"></el-table-column>
        <el-table-column prop="categoryName" label="分类" width="140"></el-table-column>
        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope">
            ¥{{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag 
              :type="statusMap[scope.row.status].type"
              :effect="statusMap[scope.row.status].effect || 'light'"
            >
              {{ statusMap[scope.row.status].label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleViewProduct(scope.row)">查看</el-button>
            <el-button size="small" type="success" @click="handleEditProduct(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 'active' ? 'danger' : 'warning'"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 'active' ? '下架' : '上架' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="mt-4 flex justify-center">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEditMode ? '编辑商品' : '添加商品'" :width="700">
      <template #default>
        <el-form
          ref="productFormRef"
          :model="formData"
          :rules="rules"
          label-width="120px"
          class="form-container"
        >
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="商品分类" prop="categoryId">
            <el-select v-model="formData.categoryId" placeholder="请选择商品分类">
              <el-option 
                v-for="category in categories" 
                :key="category.id" 
                :label="category.name" 
                :value="category.id" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品价格" prop="price">
            <el-input 
              v-model="formData.price" 
              placeholder="请输入商品价格" 
              type="number"
              min="0"
              step="0.01"
            />
          </el-form-item>
          <el-form-item label="库存数量" prop="stock">
            <el-input 
              v-model="formData.stock" 
              placeholder="请输入库存数量" 
              type="number"
              min="0"
            />
          </el-form-item>
          <el-form-item label="商品状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio label="active">上架</el-radio>
              <el-radio label="inactive">下架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="商品描述" prop="description">
            <el-input 
              v-model="formData.description" 
              placeholder="请输入商品描述" 
              type="textarea"
              rows="4"
            />
          </el-form-item>
          <el-form-item label="商品图片">
            <el-upload
              action="#"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :before-upload="beforeUpload"
              :file-list="formData.images"
              :auto-upload="false"
            >
              <el-icon><Plus /></el-icon>
              <template #file="{ file }">
                <div>
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url"
                    alt=""
                  >
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)"
                    >
                      <el-icon><ZoomIn /></el-icon>
                    </span>
                    <span
                      class="el-upload-list__item-delete"
                      @click="handleRemove(file)"
                    >
                      <el-icon><Delete /></el-icon>
                    </span>
                  </span>
                </div>
              </template>
            </el-upload>
            <el-dialog v-model="previewVisible">
              <img w-full :src="previewImage" alt="预览图片" />
            </el-dialog>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-form-item>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </el-form-item>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, ZoomIn, Delete } from '@element-plus/icons-vue'

// 路由实例
const router = useRouter()

// 模拟分类数据
const categories = ref([
  { id: 1, name: '电子数码' },
  { id: 2, name: '服装鞋帽' },
  { id: 3, name: '食品饮料' },
  { id: 4, name: '家居用品' },
  { id: 5, name: '运动户外' }
])

// 状态映射
const statusMap = {
  active: { label: '上架', type: 'success' },
  inactive: { label: '下架', type: 'info' },
  pending: { label: '审核中', type: 'warning' },
  rejected: { label: '已拒绝', type: 'danger' }
}

// 模拟商品数据
const mockProducts = [
  { 
    id: 1, 
    name: '无线蓝牙耳机', 
    categoryId: 1,
    categoryName: '电子数码',
    price: 299.99, 
    stock: 100, 
    status: 'active',
    description: '高品质无线蓝牙耳机，降噪功能，续航24小时',
    images: [{ url: 'https://picsum.photos/seed/headphone/200/200' }],
    createTime: '2023-09-01 10:30:00'
  },
  { 
    id: 2, 
    name: '纯棉T恤', 
    categoryId: 2,
    categoryName: '服装鞋帽',
    price: 59.90, 
    stock: 200, 
    status: 'active',
    description: '舒适纯棉T恤，多种颜色可选',
    images: [{ url: 'https://picsum.photos/seed/tshirt/200/200' }],
    createTime: '2023-09-02 14:15:00'
  },
  { 
    id: 3, 
    name: '智能手表', 
    categoryId: 1,
    categoryName: '电子数码',
    price: 899.00, 
    stock: 50, 
    status: 'inactive',
    description: '多功能智能手表，心率监测，运动记录',
    images: [{ url: 'https://picsum.photos/seed/watch/200/200' }],
    createTime: '2023-09-03 09:45:00'
  },
  { 
    id: 4, 
    name: '有机蔬菜礼盒', 
    categoryId: 3,
    categoryName: '食品饮料',
    price: 128.00, 
    stock: 30, 
    status: 'pending',
    description: '新鲜有机蔬菜组合礼盒，健康营养',
    images: [{ url: 'https://picsum.photos/seed/vegetable/200/200' }],
    createTime: '2023-09-04 16:20:00'
  },
  { 
    id: 5, 
    name: '折叠自行车', 
    categoryId: 5,
    categoryName: '运动户外',
    price: 1599.00, 
    stock: 15, 
    status: 'rejected',
    description: '轻便折叠自行车，便于携带，适合通勤',
    images: [{ url: 'https://picsum.photos/seed/bike/200/200' }],
    createTime: '2023-09-05 11:30:00'
  }
]

// 状态管理
const productList = ref([])
const dialogVisible = ref(false)
const isEditMode = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const localProducts = ref([...mockProducts])
const previewVisible = ref(false)
const previewImage = ref('')

// 搜索表单
const searchForm = reactive({
  name: '',
  category: '',
  status: ''
})

// 表单数据
const formData = reactive({
  id: '',
  name: '',
  categoryId: '',
  price: 0,
  stock: 0,
  status: 'active',
  description: '',
  images: []
})

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { max: 100, message: '商品名称不能超过100个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '商品价格不能为负数', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存数量不能为负数', trigger: 'blur' },
    { type: 'integer', message: '库存数量必须为整数', trigger: 'blur' }
  ]
})

// 表单引用
const productFormRef = ref(null)

// 获取商品列表
const fetchProductList = () => {
  // 应用搜索筛选
  let filtered = [...localProducts.value]
  
  if (searchForm.name) {
    filtered = filtered.filter(item => 
      item.name.toLowerCase().includes(searchForm.name.toLowerCase())
    )
  }
  
  if (searchForm.category) {
    filtered = filtered.filter(item => item.categoryId === Number(searchForm.category))
  }
  
  if (searchForm.status) {
    filtered = filtered.filter(item => item.status === searchForm.status)
  }
  
  // 模拟分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  productList.value = filtered.slice(start, end)
  total.value = filtered.length
}

// 搜索商品
const handleSearch = () => {
  currentPage.value = 1
  fetchProductList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.category = ''
  searchForm.status = ''
  currentPage.value = 1
  fetchProductList()
}

// 添加商品
const handleAddProduct = () => {
  isEditMode.value = false
  // 重置表单
  Object.keys(formData).forEach(key => {
    formData[key] = key === 'status' ? 'active' : 
                   key === 'price' || key === 'stock' ? 0 :
                   key === 'images' ? [] : ''
  })
  dialogVisible.value = true
  nextTick(() => {
    productFormRef.value?.resetFields()
  })
}

// 查看商品
const handleViewProduct = (row) => {
  router.push({ name: 'product-detail', params: { id: row.id } })
}

// 编辑商品
const handleEditProduct = (row) => {
  isEditMode.value = true
  // 复制数据到表单
  Object.keys(formData).forEach(key => {
    formData[key] = row[key]
  })
  dialogVisible.value = true
}

// 切换商品状态
const handleToggleStatus = (row) => {
  const newStatus = row.status === 'active' ? 'inactive' : 'active'
  const actionText = newStatus === 'active' ? '上架' : '下架'
  
  ElMessageBox.confirm(
    `确定要${actionText}商品"${row.name}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 更新本地数据
      const index = localProducts.value.findIndex(item => item.id === row.id)
      if (index !== -1) {
        localProducts.value[index].status = newStatus
        ElMessage.success(`${actionText}成功`)
        fetchProductList()
      }
    })
    .catch(() => {
      // 取消操作
    })
}

// 提交表单
const submitForm = () => {
  productFormRef.value?.validate(valid => {
    if (!valid) return false

    if (isEditMode.value) {
      // 更新商品
      const index = localProducts.value.findIndex(item => item.id === formData.id)
      if (index !== -1) {
        // 补充分类名称用于表格显示
        const category = categories.value.find(c => c.id === formData.categoryId)
        formData.categoryName = category?.name || ''
        
        localProducts.value[index] = { ...formData }
        ElMessage.success('更新成功')
      } else {
        ElMessage.error('商品不存在')
      }
    } else {
      // 添加商品
      // 生成新ID
      const newId = Math.max(...localProducts.value.map(item => item.id), 0) + 1
      // 补充分类名称和创建时间
      const category = categories.value.find(c => c.id === formData.categoryId)
      
      localProducts.value.push({
        ...formData,
        id: newId,
        categoryName: category?.name || '',
        createTime: new Date().toLocaleString()
      })
      ElMessage.success('添加成功')
    }
    
    dialogVisible.value = false
    fetchProductList()
  })
}

// 分页相关
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  fetchProductList()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  fetchProductList()
}

// 图片上传相关
const handlePictureCardPreview = (file) => {
  previewImage.value = file.url
  previewVisible.value = true
}

const handleRemove = (file, fileList) => {
  formData.images = fileList
}

const beforeUpload = (rawFile) => {
  // 简单的文件校验
  const isJPG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png'
  const isLt2M = rawFile.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('只能上传JPG/PNG格式的图片')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB')
    return false
  }
  
  // 模拟上传，实际项目中应调用上传接口
  const reader = new FileReader()
  reader.readAsDataURL(rawFile)
  reader.onload = (e) => {
    formData.images.push({ url: e.target.result })
  }
  
  return false // 阻止自动上传
}

// 生命周期钩子
onMounted(() => {
  fetchProductList()
})
</script>

<style scoped>
/* 自定义样式 */
.form-container {
  padding: 10px 0;
}

.el-upload--picture-card {
  width: 120px;
  height: 120px;
}
</style>